package com.zp.resource;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.springframework.stereotype.Component;

import com.sun.jersey.spi.resource.Singleton;
import com.zp.bean.common.ResultCommonVo;
import com.zp.bean.paper.PaperQuestionVo;
import com.zp.bean.paper.QuestionsVo;
import com.zp.bean.paper.ResultPaperQuestionVo;
import com.zp.domain.AnswerItem;
import com.zp.domain.Paper;
import com.zp.domain.PaperQuestion;
import com.zp.domain.Question;
import com.zp.resource.common.BaseServices;
import com.zp.util.Constant;
import com.zp.util.MyException;

/**
 * paper question services
 * 
 * @author chenlijun08@gmail.com
 * 
 * @version 1.0
 * 
 * @date 2014/2/23
 * 
 */
@Component
@Path("/rest/paperques")
@Singleton
public class PaperQuestionServices extends BaseServices {

	/**
	 * add one paper question path:/paperques/addPaperques Http:POST
	 * 
	 * @param paperques
	 * 
	 * @return Response, ResultCommonVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":0}
	 */
	@POST
	@Path("/addPaperques")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response addPaperQuestion(PaperQuestion paperques) {
		ResultCommonVo result = new ResultCommonVo();
		try {
			jpaDao.save(paperques);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * update paper question path:/paperques/updatePaperques Http:PUT
	 * 
	 * @param paperques
	 * 
	 * @return Response, ResultCommonVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":0}
	 * 
	 */
	@PUT
	@Path("/updatePaperques")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response updatePaperQuestion(PaperQuestion paperques) {
		ResultCommonVo result = new ResultCommonVo();
		try {
			jpaDao.update(paperques);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);

		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}

		return Response.ok(result).build();
	}

	/**
	 * delete paper question by paper id path:/paperques/deletePaperques
	 * Http:GET
	 * 
	 * @param paperId
	 * 
	 * @return Response, ResultCommonVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":1}
	 */
	@GET
	@Path("/deletePaperques")
	@Produces(MediaType.APPLICATION_JSON)
	public Response deletePaperQuestion(@QueryParam("paperId") String paperId) {
		logger.info("deleteQuestion called paperId:" + paperId);
		ResultCommonVo result = new ResultCommonVo();
		String jpql = "from PaperQuestion where paperId=?";
		Object[] queryParams = { paperId };
		try {
			this.jpaDao.deleteFromCriteria(jpql, queryParams);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * get all the questions by paper id path:/paperques/getQuestions Http:GET
	 * 
	 * @param paperId
	 * 
	 * @return Response, ResultPaperQuestionVo with JSON String
	 *         like:{"code":268,"message"
	 *         :"OK","totalCount":5,"paperQuestionVo":{
	 *         "paper":{"id":"402881e6445c883e01445c8a74290001"
	 *         ,"name":"心理关爱"},"list":[{"title":"心理关爱题目1","questionId":
	 *         "402881e6445cc3a301445cc4332b0001"
	 *         ,"item":[{"id":"402881e6445d4c3701445d515f8e0002"
	 *         ,"questionId":"402881e6445cc3a301445cc4332b0001"
	 *         ,"answerCode":"A",
	 *         "value":"心理关爱题目1答案1"},{"id":"402881e6445d53b401445d54be830001"
	 *         ,"questionId"
	 *         :"402881e6445cc3a301445cc4332b0001","answerCode":"B",
	 *         "value":"心理关爱题目1答案2"
	 *         },{"id":"402881e6445d53b401445d54fa180002","questionId"
	 *         :"402881e6445cc3a301445cc4332b0001"
	 *         ,"answerCode":"C","value":"心理关爱题目1答案3"
	 *         },{"id":"402881e6445d53b401445d55bb6b0003"
	 *         ,"questionId":"402881e6445cc3a301445cc4332b0001"
	 *         ,"answerCode":"D","value":"心理关爱题目1答案4"}]}]}}
	 */
	@GET
	@Path("/getQuestions")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getQuestionsByPaper(@QueryParam("pageNo") int pageNo,
			@QueryParam("pageSize") int pageSize,
			@QueryParam("paperId") String paperId) {
		logger.info("getQuestionsByPaper called pageNo is:" + pageNo
				+ " pageSize is:" + pageSize + " paperId is:" + paperId);
		ResultPaperQuestionVo result = new ResultPaperQuestionVo();
		String jpql = "from PaperQuestion where paperId=?";
		String countJpql = "select count(id) from PaperQuestion where paperId=?";
		Object[] queryParams = { paperId };
		result.setCode(Constant.SUCCESS_CODE);
		result.setMessage(Constant.OK);
		try {
			List<?> list = this.jpaDao.getResultData(pageNo, pageSize, jpql,
					queryParams);
			if (list != null && list.size() > Constant.ZERO) {
				PaperQuestionVo vo = new PaperQuestionVo();
				vo.setPaper((Paper) this.jpaDao.findById(Paper.class,
						((PaperQuestion) list.get(Constant.ZERO)).getPaperId()));
				List<QuestionsVo> listq = new ArrayList<QuestionsVo>();
				for (Object o : list) {
					PaperQuestion pq = (PaperQuestion) o;
					Question quesion = (Question) this.jpaDao.findById(
							Question.class, pq.getQuestionId());
					QuestionsVo qvo = new QuestionsVo();
					qvo.setQuestionId(quesion.getId());
					qvo.setTitle(quesion.getTitle());
					qvo.setItem(this.getItemsFromQuestion(quesion.getId()));
					listq.add(qvo);
				}
				vo.setList(listq);
				result.setPaperQuestionVo(vo);
				result.setTotalCount(this.jpaDao.getCount(countJpql,
						queryParams));
			}

		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}

		return Response.ok(result).build();
	}

	/**
	 * get answer items with question id
	 * 
	 * @param questionId
	 * 
	 * @return List<AnswerItem>
	 */
	private List<AnswerItem> getItemsFromQuestion(String questionId) {
		String jpql = "from AnswerItem where questionId=?";
		List<?> list = null;
		List<AnswerItem> lt = new ArrayList<AnswerItem>();
		Object[] param = { questionId };
		try {
			list = this.jpaDao.getResultData(Constant.NEGATIVE_ONE,
					Constant.NEGATIVE_ONE, jpql, param);
		} catch (MyException e) {
			e.printStackTrace();

		}
		if (list != null && list.size() > Constant.ZERO) {
			for (Object o : list) {
				AnswerItem aitem = (AnswerItem) o;

				lt.add(aitem);
			}

		}
		return lt;
	}
}
